package com.szgr.baoyin.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.szgr.baoyin.MyApplication;
import com.szgr.baoyin.R;
import com.szgr.baoyin.adapter.ForumDetailListAdapter;
import com.szgr.baoyin.model.ForumDetailItem;
import com.szgr.baoyin.model.ForumListItem;
import com.szgr.baoyin.utils.Constant;
import com.szgr.baoyin.utils.MyTool;
import com.szgr.baoyin.utils.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 论坛详情
 */
public class ForumDetailActivity extends Activity implements View.OnClickListener, AbsListView.OnScrollListener {

    private ForumListItem forumListItem;
    private int currentPage = 1;
    private int pageSize = 20;
    private ArrayList<ForumDetailItem> data;
    private ForumDetailListAdapter listAdapter;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 300:
                    listAdapter.setData(data);
                    break;
            }
        }
    };
    private ListView forumListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forum_detail);
        initView();
    }

    private void initView() {
        findViewById(R.id.action_bar_left).setOnClickListener(this);
        findViewById(R.id.action_bar_right).setOnClickListener(this);
        findViewById(R.id.forum_detail_reply).setOnClickListener(this);

        ImageView img_head = (ImageView) findViewById(R.id.item_forum_head_view);
        TextView tv_name = (TextView) findViewById(R.id.item_forum_name);
        TextView tv_time = (TextView) findViewById(R.id.item_forum_time);
        TextView tv_title = (TextView) findViewById(R.id.item_forum_title);
        TextView tv_content = (TextView) findViewById(R.id.item_forum_content);
        Intent intent = getIntent();
        if(intent.hasExtra("forumListItem")){
            forumListItem = (ForumListItem) intent.getSerializableExtra("forumListItem");
            MyTool.showPicture(this, img_head, forumListItem.getUserAvatar());
            tv_name.setText(forumListItem.getUser_nick_name());
            tv_title.setText(forumListItem.getTitle());
            tv_content.setText(forumListItem.getSubject());
            tv_time.setText(MyTool.getStandardDate(forumListItem.getLast_reply_date()));
        }

        data = new ArrayList<>();
        forumListView = (ListView) findViewById(R.id.forum_detail_list_view);
        listAdapter = new ForumDetailListAdapter(this, data);
        forumListView.setAdapter(listAdapter);
        forumListView.setOnScrollListener(this);

        getDetail();
    }

    private void getDetail() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_FORUM_DETAIL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("-------->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONObject head = jsonObject.getJSONObject("head");
                            String errCode = head.getString("errCode");
                            if("00000000".equals(errCode)){
                                JSONArray list = jsonObject.getJSONArray("list");
                                Gson gson = new Gson();
                                List<ForumDetailItem> forumDetailItems = gson.fromJson(list.toString(),new TypeToken<List<ForumDetailItem>>(){}.getType());
                                if(forumDetailItems != null && forumDetailItems.size() == 0) {
                                    ToastUtils.showToast("没有更多内容了");
                                }else{
                                    data.addAll(forumDetailItems);
                                    currentPage++;
                                    mHandler.obtainMessage(300).sendToTarget();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("boardId",forumListItem.getBoard_id());
                map.put("topicId",forumListItem.getTopic_id());
                map.put("page",currentPage + "");
                map.put("pageSize",pageSize + "");
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.action_bar_left:
                finish();
                break;
            case R.id.forum_detail_reply:
                Intent intent = new Intent(this,QuestionActivity.class);
                intent.putExtra("bid",forumListItem.getBoard_id());
                intent.putExtra("tid",forumListItem.getTopic_id());
                startActivityForResult(intent, 99);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if(intent != null){
            switch (resultCode){
                case 98:
                    data.clear();
                    currentPage = 1;
                    getDetail();
                    break;
            }
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if(scrollState == SCROLL_STATE_IDLE){
            if(forumListView.getLastVisiblePosition() == forumListView.getCount() - 1){
                getDetail();
            }
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }
}
